<template>
  <div class="realy-name-content">
    <van-form @submit="onSubmit">
      <div class="block">
        <div class="block-title">
          <span class="require">个人信息</span>
        </div>
        <van-field v-model="member_truename"
                   name="member_truename"
                   label="姓名："
                   placeholder="请填写真实姓名"
                   clearable
                   :readonly="!allowedEdit"
                   :rules="[{ required: true, message: '请填写真实姓名' }]" />
        <van-field v-model="member_idcard"
                   name="member_idcard"
                   label="身份证号："
                   clearable
                   :readonly="!allowedEdit"
                   placeholder="请填写身份证号码"
                   :rules="idCardNumberRules" />
      </div>

      <div class="block">
        <div class="block-title">
          <span class="require">上传身份证正反面照片</span>
        </div>
        <div class="block-tips">
          温馨提示：请上传原始比例身份证正反面，请勿裁剪涂改，保持身份证清晰显示，否则无法通过审核
        </div>
        <div class="upload flex justify-between">
          <div class="upload-content">
            <!--  -->
            <van-uploader class="upload-item"
                          :after-read="selectImage"
                          name="member_idcard_image2"
                          :disabled="!allowedEdit">
              <img class="show-img"
                   :src="member_idcard_image2.content || require('@/assets/image/id-card-2.png')" />
            </van-uploader>
            <van-field class="upload-input"
                       name="member_idcard_image2"
                       v-model="member_idcard_image2.content"
                       :rules="[{ required: true, message: '请上传身份证正面照片' }]" />
          </div>
          <div class="upload-content">
            <van-uploader class="upload-item"
                          :after-read="selectImage"
                          name="member_idcard_image3"
                          :disabled="!allowedEdit">
              <img class="show-img"
                   :src="member_idcard_image3.content || require('@/assets/image/id-card-1.png')" />
            </van-uploader>
            <van-field class="upload-input"
                       name="member_idcard_image3"
                       v-model="member_idcard_image3.content"
                       :rules="[{ required: true, message: '请上传身份证国徽面照片' }]" />
          </div>
        </div>
        <div class="submit-btn-content">
          <van-button class="btn"
                      block
                      round
                      native-type="submit"
                      v-if="allowedEdit">保存</van-button>
        </div>
      </div>
    </van-form>
  </div>
</template>

<script>
import { idCardNumberRules } from '@/utils/formRules'
import { uploadIdCard, auth } from '@/api/realyName'
import { Dialog } from 'vant'
import { mapState } from 'vuex'
export default {
  name: 'RealyName',
  data() {
    return {
      member_truename: '', // 姓名
      member_idcard: '', // 身份证号码
      member_idcard_image2: {}, // 身份证正面
      member_idcard_image3: {}, // 身份证反面
      idCardNumberRules: Object.freeze(idCardNumberRules)
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.info
    }),
    /**
     * 是否可以编辑实名认证信息
     */
    allowedEdit() {
      // 0默认  1审核中  2未通过  3已认证
      if (this.userInfo) {
        return (
          this.userInfo.member_auth_state === 0 ||
          this.userInfo.member_auth_state === 2
        )
      } else {
        return true
      }
    }
  },
  watch: {
    userInfo(newVal, oldVal) {
      // 初始化用户信息
      this.member_truename = this.userInfo.member_truename
      this.member_idcard = this.userInfo.member_idcard
      this.member_idcard_image2 = {
        content: this.userInfo.member_idcard_image2_url,
        status: this.userInfo.member_idcard_image2_url !== ''
      }
      this.member_idcard_image3 = {
        content: this.userInfo.member_idcard_image3_url,
        status: this.userInfo.member_idcard_image2_url !== ''
      }
    }
  },
  methods: {
    /**
     * 提交实名信息
     */
    onSubmit(formData) {
      Dialog.confirm({
        title: '提示',
        message: '请仔细核对信息，确认上传后无法重新编辑'
      }).then(() => {
        // 上传图片
        this.uploadImg(status => {
          // 图片上传成功才提交信息
          if (status) {
            auth({
              member_truename: this.member_truename,
              member_idcard: this.member_idcard,
              if_confirm: true
            })
              .then(res => {
                this.$toast({
                  message: res.message || '提交成功',
                  type: 'success',
                  onClose: () => {
                    this.$router.go(-1)
                  }
                })
              })
              .catch(res => {
                this.$toast({
                  type: 'fail',
                  message: res.message
                })
              })
          }
        })
      })
    },
    /**
     * 上传图片
     * @function cbFn 上传图片后的回调函数
     */
    uploadImg(cbFn) {
      let queue = [] // 上传的队列
      Promise.all(
        ['member_idcard_image2', 'member_idcard_image3'].map(item => {
          let fileInfo = this[item]
          // 没上传过的图片才进行上传
          if (!fileInfo.status) {
            let formData = new FormData()
            formData.append('id', item)
            formData.append(item, fileInfo.file)
            queue.push(item)
            return uploadIdCard(formData)
          }
        })
      )
        .then(res => {
          queue.forEach(item => {
            this[item].status = true
          })
          cbFn(true)
        })
        .catch(res => {
          this.$toast({
            type: 'fail',
            message: res.message
          })
          cbFn(false)
        })
    },

    /**
     * 选择图片后存储图片和展示
     */
    selectImage(file, { name }) {
      file.status = false // 标识为未上传
      this[name] = file
    }
  }
}
</script>

<style lang="scss">
.realy-name-content {
  font-size: 16px;
  .block {
    padding: 10px 0;
    & + .block {
      border-top: 10px solid #f5f6fa;
    }

    .block-title {
      padding: 10px 15px;
      font-size: 16px;
      color: #000000;
      .require {
        padding-left: 13px;
        position: relative;
        &::before {
          position: absolute;
          content: '*';
          color: $mainColor;
          top: 50%;
          left: 0;
          transform: translateY(-25%);
          font-size: 18px;
        }
      }
    }

    .block-tips {
      padding: 5px 15px;
      color: #999999;
      font-size: 13px;
      line-height: 1.5;
    }

    .upload {
      padding: 14px;
      height: 160px;
      .upload-content {
        position: relative;
        width: 100%;
        & + .upload-content {
          margin-left: 7.5px;
        }
        .upload-item {
          position: absolute;
          top: 0;
          left: 0;
          z-index: 100;
          .show-img {
            top: 0;
            left: 0;
            width: 170px;
            height: 120px;
          }
        }
        .upload-input {
          position: absolute;
          bottom: -30px;
          left: 0;
          width: 100%;
          /deep/ .van-field__control {
            opacity: 0;
          }
        }
      }
    }
    .submit-btn-content {
      padding: 15px 20px;
      .btn {
        color: #fff;
        background-color: $mainColor;
      }
    }
  }
}
</style>
